﻿#include "buss_menu.h"
#include "ui_buss_menu.h"
#include "buss_main.h"
#include "buss_addmenu.h"

#include <QLabel>
#include <QPushButton>
#include <QMessageBox>
#include <QSqlError>
#include <QFile>
#include <QDoubleSpinBox>
#include <QTextEdit>
#include <QFileDialog>
#include <QDebug>
#include <QComboBox>
#include <QFrame> // Added for QFrame
#include <QScreen>
#include <QGuiApplication>
Buss_menu::Buss_menu(int bus_id,QWidget *parent) :
    bus_id(bus_id),
    QWidget(parent),
    ui(new Ui::Buss_menu)
{
    ui->setupUi(this);
    setWindowTitle("菜单管理");    
    resize(1250, 800);
    setMinimumSize(1000, 600);    
    // 在构造函数中设置scrollArea的属性
    ui->scrollArea->setWidgetResizable(true);
    ui->scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    ui->scrollAreaWidgetContents->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
    ui->scrollAreaWidgetContents->setMinimumWidth(0);
    ui->scrollArea->setMinimumWidth(1120); // 与UI文件中设置的宽度一致
    
    setupDatabase();
    refreshMenuList();

    // 回车键触发搜索
    connect(ui->lineEdit, &QLineEdit::returnPressed, this, &Buss_menu::on_pushButton_serach_clicked);
}

Buss_menu::~Buss_menu()
{
    db.close();
    delete ui;
}
void Buss_menu::setupDatabase()
{
    db = QSqlDatabase::database();
    if (!db.isOpen()) {
        if (!db.open()) {
            QMessageBox::critical(this, "错误", "无法连接数据库: " + db.lastError().text());
            qDebug() << "数据库连接失败:" << db.lastError().text();
        }
    }
}
//跳转添加菜品
void Buss_menu::on_pushButton_add_clicked()
{
    Buss_addmenu *addMenu = new Buss_addmenu(bus_id);
    // 使用旧式的SIGNAL/SLOT宏语法连接，这种方式更容易处理重载函数
    connect(addMenu, SIGNAL(menuAdded()), this, SLOT(refreshMenuList()));
    addMenu->show();
}
//带参
void Buss_menu::refreshMenuList(const QString &searchText)
{
    clearMenuList();
    QWidget *container = ui->scrollAreaWidgetContents;
    QVBoxLayout *layout = new QVBoxLayout(container);
    container->setLayout(layout);

    QSqlQuery query;

    if (searchText.isEmpty()) {
        query.prepare("SELECT com_id, com_name, price, number, img, description, cs_id FROM commodity WHERE business_id = :business_id");
        query.bindValue(":business_id", bus_id);
    } else {
        query.prepare("SELECT com_id, com_name, price, number, img, description, cs_id FROM commodity WHERE business_id = :business_id AND com_name LIKE :searchText");
        query.bindValue(":business_id", bus_id);
        query.bindValue(":searchText", "%" + searchText + "%");
    }

    if (!query.exec()) {
        QMessageBox::critical(this, "错误", "查询商品失败: " + query.lastError().text());
        return;
    }

    while (query.next()) {
        int id = query.value(0).toInt();
        QString name = query.value(1).toString();
        double price = query.value(2).toDouble();
        int number = query.value(3).toInt(); // 销量
        QString img = query.value(4).toString();
        QString description = query.value(5).toString();
        int saleId = query.value(6).toInt();
        // 查询状态文本
      QSqlQuery statusQuery;
      statusQuery.prepare("SELECT status FROM commodity_status WHERE cs_id = :cs_id");
      statusQuery.bindValue(":cs_id", saleId);
      statusQuery.exec();
      QString statusText = "未知状态";
      if (statusQuery.next()) {
          statusText = statusQuery.value(0).toString();
      }
        // 在每个菜单项之间添加分隔线
        if (layout->count() > 0) {
            QFrame *line = new QFrame();
            line->setFrameShape(QFrame::HLine);
            line->setFrameShadow(QFrame::Sunken);
            line->setStyleSheet("color: #eee;");
            layout->addWidget(line);
        }
        // 创建菜品项容器
        QWidget *itemWidget = new QWidget();
        QHBoxLayout *itemLayout = new QHBoxLayout(itemWidget);
        itemWidget->setStyleSheet("QWidget { background-color: white; border-radius: 5px; margin: 5px; padding: 10px; }");
        // itemWidget高度自适应，宽度自适应scrollArea
        itemWidget->setMinimumWidth(1000); // 可根据实际窗口宽度调整
        itemWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum);
        // 修改itemLayout的边距
        itemLayout->setContentsMargins(15, 10, 15, 10);
        itemLayout->setSpacing(15);
        // 添加图片显示
         QLabel *imageLabel = new QLabel();
         // 图片区
         imageLabel->setFixedSize(100, 100);
         imageLabel->setAlignment(Qt::AlignCenter);
         imageLabel->setStyleSheet("QLabel { border: 1px solid #ddd; border-radius: 4px; padding: 2px; background-color: #f5f5f5;}");

          if (!img.isEmpty() && QFile::exists(img)) {
            QPixmap pixmap(img);
               if (!pixmap.isNull()) {
                  pixmap = pixmap.scaled(imageLabel->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
                  imageLabel->setPixmap(pixmap);
                    } else {
                  imageLabel->setText("无图片");
                  imageLabel->setStyleSheet("QLabel { color: #999; font-style: italic; }");
                    }
                } else {
                 imageLabel->setText("无图片");
                 imageLabel->setStyleSheet("QLabel { color: #999; font-style: italic; }");
                }

          // 信息区
          QVBoxLayout *infoLayout = new QVBoxLayout();
          infoLayout->setSpacing(5); // 设置内部间距
          infoLayout->setContentsMargins(0, 0, 0, 0);
          // 菜品名
          QLabel *nameLabel = new QLabel(name);
          nameLabel->setStyleSheet("font-size: 16px; font-weight: bold;");
          nameLabel->setWordWrap(true);
          nameLabel->setMaximumHeight(72); // 支持两行显示
          infoLayout->addWidget(nameLabel);
          // 状态标签
          QLabel *statusLabel = new QLabel(statusText);
          statusLabel->setStyleSheet(
              "font-size: 12px;"
              "color: white;"
              "background-color: #67C23A;"
              "padding: 2px 8px;"
              "border-radius: 10px;"
          );
          infoLayout->addWidget(statusLabel);
          // 价格
          QLabel *priceLabel = new QLabel(QString("价格：¥%1").arg(price, 0, 'f', 2));
          priceLabel->setStyleSheet("font-size: 14px; color: #E6A23C; font-weight: bold;");
          infoLayout->addWidget(priceLabel);
          // 销量
          QLabel *numberLabel = new QLabel(QString("销量：%1").arg(number));
          numberLabel->setStyleSheet("font-size: 13px; color: #43A047; font-weight: bold;");
          infoLayout->addWidget(numberLabel);
          // 描述
          QLabel *descLabel = new QLabel(QString("描述：%1").arg(description));
          descLabel->setStyleSheet("font-size: 13px; color: #666; max-height: 80px;");
          descLabel->setWordWrap(true);
          descLabel->setMaximumHeight(80); // 放宽最大高度
          infoLayout->addWidget(descLabel);
          infoLayout->addStretch();
          QWidget *infoWidget = new QWidget();
          infoWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
          infoWidget->setLayout(infoLayout);

          // 按钮区
          QPushButton *editButton = new QPushButton("编辑");
          // 编辑/删除按钮更大
          editButton->setFixedSize(120, 48);
          QPushButton *deleteButton = new QPushButton("删除");
          // 编辑/删除按钮更大
          deleteButton->setFixedSize(120, 48);
          // 更明显的按钮样式
          QString buttonStyle =
              "QPushButton {"
              "   min-width: 120px;"
              "   min-height: 48px;"
              "   max-width: 120px;"  // 添加最大宽度限制
              "   max-height: 48px;"  // 添加最大高度限制
              "   padding: 10px 18px;"
              "   border-radius: 8px;"
              "   font-size: 22px;"
              "   font-weight: bold;"
              "   letter-spacing: 2px;"
              "   box-shadow: 0 2px 8px rgba(0,0,0,0.12);"
              "   border: 2px solid #1976D2;"
              "   background-color: #1976D2;"
              "   color: #fff;"
              "}"
              "QPushButton#delete { border-color: #D32F2F; background-color: #D32F2F; }"
              "QPushButton:hover { filter: brightness(1.15); border-width: 3px; }";
          editButton->setObjectName("edit");
          deleteButton->setObjectName("delete");
          editButton->setStyleSheet(buttonStyle);
          deleteButton->setStyleSheet(buttonStyle);
          // 统一按钮样式
          // QString buttonStyle =
          //     "QPushButton {"
          //     "   min-width: 80px;"
          //     "   min-height: 35px;"
          //     "   padding: 5px 10px;"
          //     "   border-radius: 4px;"
          //     "   font-size: 13px;"
          //     "}"
          //     "QPushButton:hover { opacity: 0.9; }";

          // editButton->setStyleSheet(buttonStyle + "background-color: #409EFF; color: white;");
          // deleteButton->setStyleSheet(buttonStyle + "background-color: #F56C6C; color: white;");

          QVBoxLayout *buttonLayout = new QVBoxLayout();
          buttonLayout->addStretch();
          buttonLayout->addWidget(editButton, 0, Qt::AlignHCenter);
          buttonLayout->addWidget(deleteButton, 0, Qt::AlignHCenter);
          buttonLayout->addStretch();
          buttonLayout->setSpacing(24);
          buttonLayout->setContentsMargins(0, 0, 0, 0);
          QWidget *buttonWidget = new QWidget();
          buttonWidget->setLayout(buttonLayout);
          buttonWidget->setFixedWidth(160); // 增加按钮区域宽度
          buttonWidget->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding);
          // 按钮区加背景色便于调试
          buttonWidget->setStyleSheet("");

          // 添加到主布局
          itemLayout->addWidget(imageLabel, 0);
          itemLayout->addWidget(infoWidget, 1); // 信息区拉伸因子大
          itemLayout->addWidget(buttonWidget, 0);
          // 设置拉伸因子，给按钮区域更多空间
          itemLayout->setStretch(0, 1); // imageLabel
          itemLayout->setStretch(1, 3); // infoWidget (信息区域)
          itemLayout->setStretch(2, 1); // buttonWidget (按钮区域)
          layout->addWidget(itemWidget);

          // 按钮操作
          QObject::connect(editButton, &QPushButton::clicked, [this, id, name, price, description, img]() {
              // 打开编辑界面
              editMenuItem(id, name, price, description, img);
          });
          QObject::connect(deleteButton, &QPushButton::clicked, [this, id]() {
              // 删除功能实现
              QSqlQuery deleteQuery;
              deleteQuery.prepare("DELETE FROM commodity WHERE com_id = :id");
              deleteQuery.bindValue(":id", id);
              if (deleteQuery.exec()) {
                  QMessageBox::information(this, "成功", "商品删除成功!");
                  refreshMenuList();
              } else {
                  QMessageBox::critical(this, "错误", "删除失败: " + deleteQuery.lastError().text());
              }
          });
    }
}
void Buss_menu::refreshMenuList()
{
    refreshMenuList(""); // 调用带参数的版本
}
void Buss_menu::clearMenuList()
{
    QWidget *container = ui->scrollAreaWidgetContents;
    QLayout *layout = container->layout();

    if (layout) {
        QLayoutItem *item;
        while ((item = layout->takeAt(0))) {
            if (item->widget()) {
                           item->widget()->deleteLater();
                       }
                       delete item;
                   }
                   delete layout;
               }
    m_currentEditImagePath.clear();
}

//跳转菜单主界面
void Buss_menu::on_pushButton_return_clicked()
{
    Buss_main *b=new Buss_main;
    b->setBusiness1_id(bus_id);
    b->show();
    this->hide();
    return;
}

//刷新菜单界面
void Buss_menu::on_pushButton_refresh_clicked()
{
    refreshMenuList();
}
//编辑的对话框
void Buss_menu::editMenuItem(int id, const QString &name, double price, const QString &description, const QString &imgPath)
{
     m_currentEditImagePath.clear();
    // 创建编辑对话框
    QDialog *editDialog = new QDialog(this);
    editDialog->setWindowTitle("编辑菜品");
    editDialog->setFixedSize(400, 500);

    QVBoxLayout *layout = new QVBoxLayout(editDialog);

    // 菜品名称
    QLabel *nameLabel = new QLabel("菜品名称:");
    QLineEdit *nameEdit = new QLineEdit(name);

    // 价格
    QLabel *priceLabel = new QLabel("价格:");
    QDoubleSpinBox *priceSpin = new QDoubleSpinBox();
    priceSpin->setRange(0, 999);
    priceSpin->setSingleStep(0.5);
    priceSpin->setValue(price);

    // 描述
    QLabel *descLabel = new QLabel("描述:");
    QTextEdit *descEdit = new QTextEdit(description);

    // 添加状态选择
    QLabel *statusLabel = new QLabel("状态:");
    QComboBox *statusCombo = new QComboBox();
    statusCombo->addItem("上架", 3);
    statusCombo->addItem("下架", 1);

    // 从数据库填充状态选项
    QSqlQuery statusQuery;
    statusQuery.prepare("SELECT cs_id FROM commodity WHERE com_id = :id");
    statusQuery.bindValue(":id", id);
    if (statusQuery.exec() && statusQuery.next()) {
         int currentStatus = statusQuery.value(0).toInt();
         for (int i = 0; i < statusCombo->count(); ++i) {
             if (statusCombo->itemData(i).toInt() == currentStatus) {
                 statusCombo->setCurrentIndex(i);
                    break;
                }
            }
        }
      // 添加到布局
      layout->addWidget(statusLabel);
      layout->addWidget(statusCombo);

    // 图片显示和更换
    QLabel *imageLabel = new QLabel();
    imageLabel->setAlignment(Qt::AlignCenter);
    imageLabel->setFixedSize(150, 150);
    imageLabel->setStyleSheet(
        "QLabel {"
        "border: 2px dashed #aaa;"
        "border-radius: 5px;"
        "background-color: #f9f9f9;"
        "padding: 10px;"
        "}"
        "QLabel a { color: blue; text-decoration: underline; }"
    );
    imageLabel->setTextFormat(Qt::RichText);
    imageLabel->setOpenExternalLinks(false);

    // 添加清除图片按钮
    QPushButton *clearImageButton = new QPushButton("清除图片");
    clearImageButton->setStyleSheet(
        "QPushButton {"
        "background-color: #F56C6C;"
        "color: white;"
        "border-radius: 4px;"
        "padding: 5px 10px;"
        "}"
        "QPushButton:hover { background-color: #F78989; }"
    );
    clearImageButton->setVisible(false); // 初始隐藏

    // 显示当前图片
    if (!imgPath.isEmpty() && QFile::exists(imgPath)) {
        QPixmap pixmap(imgPath);
        if (!pixmap.isNull()) {
            pixmap = pixmap.scaled(imageLabel->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
            imageLabel->setPixmap(pixmap);
            imageLabel->setText("<a href='change'>点击更换图片</a>");
            clearImageButton->setVisible(true); // 有图片时显示清除按钮
        } else {
            imageLabel->setText("<a href='change'>点击添加图片</a>");
            clearImageButton->setVisible(false);
        }
    } else {
        imageLabel->setText("<a href='change'>点击添加图片</a>");
        clearImageButton->setVisible(false);
    }

    // 图片点击事件处理
    connect(imageLabel, &QLabel::linkActivated, this,&Buss_menu::getImg);

    // 清除图片按钮事件
    connect(clearImageButton, &QPushButton::clicked, [this, imageLabel, clearImageButton]() {
        imageLabel->clear();
        imageLabel->setText("<a href='change'>点击添加图片</a>");
        m_currentEditImagePath = "CLEARED"; // 设置特殊标记表示图片被清除
        clearImageButton->setVisible(false);
        qDebug() << "已清除图片";
    });

    // 按钮
    QPushButton *saveButton = new QPushButton("保存");
    QPushButton *cancelButton = new QPushButton("取消");

    QHBoxLayout *buttonLayout = new QHBoxLayout();
    buttonLayout->addStretch();
    buttonLayout->addWidget(saveButton);
    buttonLayout->addWidget(cancelButton);

    // 添加到布局
    layout->addWidget(nameLabel);
    layout->addWidget(nameEdit);
    layout->addWidget(priceLabel);
    layout->addWidget(priceSpin);
    layout->addWidget(descLabel);
    layout->addWidget(descEdit);
    layout->addWidget(imageLabel);
    
    // 图片操作按钮布局
    QHBoxLayout *imageButtonLayout = new QHBoxLayout();
    imageButtonLayout->addWidget(clearImageButton);
    imageButtonLayout->addStretch();
    layout->addLayout(imageButtonLayout);
    
    layout->addLayout(buttonLayout);

    // 连接按钮信号
    connect(saveButton, &QPushButton::clicked, [=]() {
        QString newName = nameEdit->text();
        double newPrice = priceSpin->value();
        QString newDesc = descEdit->toPlainText();
        int newStatus = statusCombo->currentData().toInt();

        if (newName.isEmpty()) {
            QMessageBox::warning(this, "警告", "菜品名称不能为空!");
            return;
        }

        // 确定要保存的图片路径

        if (m_currentEditImagePath == "CLEARED") {
            // 如果用户清除了图片
            finalImagePath = "";
            qDebug() << "图片已被清除";
        } else if (!m_currentEditImagePath.isEmpty()) {
            // 如果选择了新图片，使用新图片路径
            finalImagePath = m_currentEditImagePath;
            qDebug() << "使用新选择的图片:" << finalImagePath;
        } else {
            // 否则使用原图片路径
            finalImagePath = imgPath;
            qDebug() << "保持原图片:" << finalImagePath;
        }

        QSqlQuery query;
        query.prepare("UPDATE commodity SET com_name = :name, price = :price, "
                              "description = :desc, img = :img, cs_id = :status WHERE com_id = :id");
        query.bindValue(":name", newName);
        query.bindValue(":price", newPrice);
        query.bindValue(":desc", newDesc);
        query.bindValue(":img", finalImagePath);
        query.bindValue(":status", newStatus);
        query.bindValue(":id", id);
        
        if (query.exec()) {
            QMessageBox::information(this, "成功", "菜品信息已更新!");
            editDialog->close();
            refreshMenuList();
        } else {
            QMessageBox::critical(this, "错误", "更新失败: " + query.lastError().text());
            qDebug() << "SQL错误:" << query.lastError().text();
        }
    });

    connect(cancelButton, &QPushButton::clicked, editDialog, &QDialog::close);

    editDialog->exec();
}
void Buss_menu::getImg(){
    m_currentEditImagePath = database::copyImageToDirectory("../img");
    qDebug()<<"图片地址："<<m_currentEditImagePath;
}
//搜索按钮
void Buss_menu::on_pushButton_serach_clicked()
{
    QString searchText = ui->lineEdit->text().trimmed();
    refreshMenuList(searchText);
}
